<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/webpage/include/taglib.jsp" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>植百汇采购单</title>
    <script>
        var ctx = '${ctx}';
        var purchaseOrderId='${purchaseOrderId}';
    </script>
    <script type="text/javascript" src="${ctxStatic}/plugin/layui2.0/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="${ctxStatic}/plugin/layui2.0/layui.js"></script>
    <link rel="stylesheet" href="${ctxStatic}/plugin/layui2.0/css/layui.css" media="all">
    <link rel="stylesheet" href="${ctxStatic}/common/css/app-blue.css" media="all"> 
    <script src="${ctxStatic}/common/js/jeeplus.js"></script>
     <%@ include file="/webpage/include/bootstraptable.jsp"%>
     <link rel="stylesheet" href="${ctxStatic}/purchase/add_purchase.css" media="all">
</head>
<body style="width:100%; height:100%; overflow: scroll; -webkit-overflow-scrolling: touch;">
	<div class="wrapper wrapper-content">				
			<div class="row">
				<div class="col-md-12">
					<div class="panel panel-primary">
						<div class="panel-heading">
							<h3 class="panel-title">
							<span style="font-size:12px">采购单修改  </span> 
								<a class="panelButton" href="${ctx}/purchase/purchaseOrder"><i class="ti-angle-left"></i> 返回</a>
								<!-- <span class="panel-title margin-left-3">采购单录入</span> -->
							</h3>
						</div>
						<div class="panel-body">
						    <form class="layui-form" action="">
						        <!--供应商信息start-->
						        <div class="row">
						            <div class="col-xs-12 col-sm-6 col-md-3">
						                <label class="label-txt col-xs-4 col-sm-3">供应商:</label>
						                <div class="layui-input-inline col-xs-8 col-sm-9">
						                    <select id="supplierId" lay-filter="supplierId" name="supplierId" lay-verify="required" lay-search="">
							                    <c:if test="${purOrder.supplierId!=null}"> <option selected value="${purOrder.supplierId}">${purOrder.supplierName}</option></c:if>
						                    </select>
						                </div>
						            </div>
						            <%--暂时注释 没有合同 但是往后台传递是该字段要有值 为null 或者"" --%>
						        <div class="col-xs-12 col-sm-6 col-md-3">
						                <label class="label-txt col-xs-4 col-sm-3" >供应商合同:</label>
						                <div class="layui-input-inline col-xs-8 col-sm-9">
						                    <select name="contractId" id="contractId" lay-verify="required" lay-search="">
						                      <c:if test="${purOrder.contractId!=null}"><option selected value="${purOrder.contractId}">${purOrder.contractName}</option></c:if>
						                    </select>
						                </div>
						            </div>
						        </div>
						        <!--供应商信息end-->
						    
						        <div class="row remarkRow">
							        <div class="col-xs-12 col-sm-9 col-md-9 ">
							        	 <label class='label-txt col-xs-4 col-sm-3 '>备注:</label>
							            <div class="layui-input-inline col-xs-8 col-sm-11">
							                <textarea id="remarks" name="remarks" placeholder="请输入内容" class="layui-textarea">${purOrder.remarks}</textarea>
							            </div>
							        </div>
						        </div>
						         <!-- 工具栏 -->
						         <div id="toolbar">
				                        <a  class="btn btn-primary" href="javascript:;"  onclick="sub()"><i
				                                class="glyphicon glyphicon-plus"></i> 选择SKU</a>
				                         <span  class="btn  btn-info" onclick="subForm()">
				                            <i class="glyphicon glyphicon-save"></i> 暂存
				                        </span>
				                        <span  class="btn btn-danger" onclick="reBack()">
				                            <i class="glyphicon glyphicon-remove"></i> 返回
				                        </span>
				                </div>
				                <!-- 工具栏 -->
						        <style>
						                #purchaseOrder .self-adaption-wrap {
						                   overflow-x: scroll;
						               }
						               .self-adaption-wrap::-webkit-scrollbar {
						                   display: none;
						               }
						               #purchaseOrder .self-adaption-input{
						                   min-width: 200px;
						               }
						        </style>
						        <!--动态添加数据start-->
						        <div>
						        	<table id="purchaseOrder" data-toolbar="#toolbar"></table>
						        </div>
						        	
						        <!--动态添加数据end-->
						        <hr/>
						    </form>
						</div>
					</div>
				</div>
			</div>
		</div>
 </body>
<!-- 注意：如果你直接复制所有代码到本地，上述js路径需要改成你本地的 -->
<script>
    layui.use(['form', 'layedit', 'laydate'], function () {
        var form = layui.form
            , layer = layui.layer
            , layedit = layui.layedit
            , laydate = layui.laydate;

        <!--清空sku搜索状态-->
        form.on('select(sku)', function (data) {
            if(""==data.value){
                form.render('select')
            }
        });
    });
</script>
<script>
    function subForm() {
    	var json = new Object();
	    json.contractId=$("#contractId").val()==''?null:$("#contractId").val();//供应商合同
	    json.supplierId=$("#supplierId").val()==''?null:$("#supplierId").val();//供应商id
	    json.remarks = $("#remarks").val();//备注
	    var items = $("#purchaseOrder>tbody>tr");
        //采购明细单
	    if(null==items || ""==items || items.length==0){
	        layer.alert('请添加sku!', {
	            icon: 2,
	            title: "提示"
	        });
	        return;
	    }

	    var orderItems = new Array();
	    var orderItem;
	    for (var i = 0; i < items.length; i++) {
	        orderItem = new Object();
	        orderItem.skuId = $(items[i]).find("[name='sku']").val();
	        orderItem.price = $(items[i]).find("#price").val();
	        orderItem.num = $(items[i]).find("#num").val();

	        if (orderItem.skuId == "" || orderItem.price == "" || orderItem.num == "") {
	            layer.alert('有空数据请检查!', {
	                icon: 2,
	                title: "提示"
	            }); 
	           // jp.error("有空数据！");
	            return;
	        }
	        if(orderItem.num == "0"){
	        	layer.alert('采购数量不可以为0!', {
	                icon: 2,
	                title: "提示"
	            }); 
	            return;
	        }
	      //移动端数字处理
	        var reg = /^[1-9]\d*$/;
	        if(!reg.test(orderItem.num)){
	        	layer.alert('采购数量不可包含非数字', {
	                icon: 2,
	                title: "提示"
	            }); 
	            return;
	        }
	        var reg2 =/^((0{1}\.\d{1,2})|([1-9]\d*\.{1}\d{1,2})|([1-9]+\d*)|0)$/;
	        if(!reg2.test(orderItem.price)){
	        	layer.alert('价格必须是数字', {
	                icon: 2,
	                title: "提示"
	            }); 
	            return;
	        }

	        orderItems.push(orderItem);
	    }
	    json.items = orderItems;
        json.purchaseOrderId=purchaseOrderId;
        var fromData=new FormData();
        fromData.append("remarks",$("#remarks").val());
        fromData.append("jsons",JSON.stringify(json));
	    //提交数据
 	    $.ajax({
	        url: "${ctx}/purchase/purchaseOrder/savePurchaseOrder",
	        type: "post",
	        data: fromData,
	        contentType: false, // 注意这里应设为false
	        processData: false,
	        beforeSend: function () {
	            index = layer.load(1, {
	                shade: [0.5, '#fff'] //0.1透明度的白色背景
	            });
	        },
	        complete: function () {
	            layer.close(index);
	        },
	        success: function (data) {
	            if (data.message == "1") {
	                layer.alert('保存成功!', {
	                    icon: 1,
	                    title: "提示"
	                });
	                layer.close(index);
	                reBack();
	            }
	        },
	        error: function (e) {
	            layer.alert('保存失败!', {
	                icon: 2,
	                title: "提示"
	            });

	        }
	    }); 
    }
    function reBack() {
        window.location.href="${ctx}/purchase/purchaseOrder/list";
    }
</script>
<script>
/*     //弹窗选择sku
    function sub() {
        layer.open({
            type: 2,
            title: 'sku选择',
            maxmin: true, //开启最大化最小化按钮*!/
            area: ['1200px', '600px'],
            content:ctx+"/sku/sku/pop",
            btn:['确定','取消'],
            yes : function(index,layero) {

                var rows=$(layero).find("iframe")[0].contentWindow.$("#skuTable").bootstrapTable('getSelections');

                if(null!=rows){
                	var count = $('#purchaseOrder').bootstrapTable('getData').length;
               	    var dataArr = $('#purchaseOrder').bootstrapTable('getData');
               	 	var hasThead = $('#purchaseOrder>thead').length;
	               	 if(hasThead>0){//有头部表示已经生成过表格
	               		for(var i = 0; i < count; i++){
                            // 获取父级元素
                	            var eleParent = $('#purchaseOrder>tbody>tr:eq('+i+')');
                	            // 获取每个row对应field的值
                	            dataArr[i]['amount'] = eleParent.find("[name='num']").val();
                	            dataArr[i]['price'] = eleParent.find("[name='price']").val();
                	            console.log( dataArr[i]['amount'], dataArr[i]['amount']);
                	            // 更新option中的值
                	            $('#purchaseOrder').bootstrapTable('getOptions').data.splice(i, 1, dataArr[i]);
                        	}
                         	$.each(rows,function(idx,o){
                         	 	o.skuId=o.id;
                             	let skuName=o.productName+"：" + "["+jp.getDictLabel(${fns:toJson(fns:getDictList('sc_category_a'))}, o.categoryA, "-")+"]" +"—" +"["+jp.getDictLabel(${fns:toJson(fns:getDictList('sc_category_b'))},o.categoryB, "-")+"]" +"—" +"["+jp.getDictLabel(${fns:toJson(fns:getDictList('sc_category_c'))}, o.categoryC, "-")+"]";
                             	let res=checkSkuName(o.id);//校验是否重复
                             	if(!res){
                             	// 更新新建的row并添加到table中
                                  	 $('#purchaseOrder').bootstrapTable('insertRow',{
                                 		 index:count,
                                 		 row:{
                                 		 	skuId: o.skuId,
                                   	 		amount:o.amount,
                                   	 		skuName:skuName,
                                   	 		price:o.price 
                                 		 }
                                  });
                             	}
                         	});
	           	 }
                }
            }
        });
    } */
    //弹窗选择sku
    function sub() {
        layer.open({
            type: 2,
            title: 'sku选择',
            maxmin: true, //开启最大化最小化按钮*!/
            area: ['96%', '80%'],
            offset: '10px',
            content:ctx+"/sku/sku/pop",
            btn:['确定','取消'],
            yes : function(index,layero) {
                var rows=$(layero).find("iframe")[0].contentWindow.$("#skuTable").bootstrapTable('getSelections');
                if(null!=rows){
                	 var count = $('#purchaseOrder').bootstrapTable('getData').length;
                	 var dataArr = $('#purchaseOrder').bootstrapTable('getData');
                	 var hasThead = $('#purchaseOrder>thead').length;
                	 if(hasThead>0){//有头部表示已经生成过表格
                		  var nextIndex;
                          for(var i = 0; i < count; i++){
                          // 获取父级元素
          	                var eleParent = $('#purchaseOrder>tbody>tr:eq('+i+')');
          	                // 获取每个row对应field的值
          	                dataArr[i]['amount'] = eleParent.find("[name='num']").val();
          	                dataArr[i]['price'] = eleParent.find("[name='price']").val();
          	                console.log( dataArr[i]['amount'], dataArr[i]['amount']);
          	                // 更新option中的值
          	                $('#purchaseOrder').bootstrapTable('getOptions').data.splice(i, 1, dataArr[i]);
                      	}
                        	$.each(rows,function(idx,o){
                        		 o.skuId=o.id;
                            	 let skuName=o.productName+"：" + "["+jp.getDictLabel(${fns:toJson(fns:getDictList('sc_category_a'))}, o.categoryA, "-")+"]" +"—" +"["+jp.getDictLabel(${fns:toJson(fns:getDictList('sc_category_b'))},o.categoryB, "-")+"]" +"—" +"["+jp.getDictLabel(${fns:toJson(fns:getDictList('sc_category_c'))}, o.categoryC, "-")+"]";
                            	 let res=checkSkuName(o.id);//校验是否重复
                            	 if(!res){
                            	 // 新建下一个row
                                        var insertRow = o;
                                        // 给下一个row赋值
                                        var params = {index:count + 1, row:insertRow};
                                        // 更新新建的row并添加到table中
                                       // if(oneKey){//一键导入的数据格式与选择sku生成的不一致
                                        	 $('#purchaseOrder').bootstrapTable('insertRow',{
                                     			 index:count,
                                     			 row:{
                                     				 skuId: o.skuId,
                                         			 amount:o.amount,
                                         			 skuName:skuName,
                                         			 price:o.price 
                                     			 }
                                     	 });
                                       /*  }else{
                                        	$('#purchaseOrder').bootstrapTable('insertRow', params);
                                        } */
                            	 }
                        	});
                	 }else{
                		 $.each(rows,function(idx,o){
                			 o.skuId=o.id;
                		 });
                		 createTableData(rows);
                		 if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端
                			 $('#purchaseOrder').bootstrapTable("toggleView");
                		 }
                	 }
                }
            }
        });
    }
    //校验sku是否重复
    function checkSkuName(id) {
        var k=0;
        var skus=$("#purchaseOrder").find("input[name='sku']");
        for(var i=0;i<skus.length;i++){
            if(id==$(skus[i]).val()){
                layer.alert('已存在相同的sku!', {
                    icon: 3,
                    title: "提示"
                });
                k=1;
            }
        }
        return k;
    }

    //添加
    function addItem(skuName,skuId) {
        var sku=$("#item").find("input[name='sku']");
        $(sku).attr("value",skuName);
        $(sku).attr("sku",skuId);
        var html="<div class=\"layui-form-item\" >"+$("#item").html()+"</div>";
        $("#purchaseOrder").append(html);
    }

    //删除
    function removeItem(obj,skuId) {
    	jp.confirm('确认要删除该SKU吗？', function(){
    		var $patr =$(obj).parents("tr");
    		//将该数据从数据源删除 
    		rowData =$('#purchaseOrder').bootstrapTable('getData');
    		//记录当前页面填写的数据
    		var $currentTrs = $("#purchaseOrder>tbody>tr:not(.detail-view)");
    		for(var x=0;x<$currentTrs.length;x++){
    			var $tr = $($currentTrs[x]);
    			var currentSkuId = $tr.find("[name='sku']").val();
    			if(currentSkuId==rowData[x].skuId){
    				//格式修改
    				rowData[x].amount=$tr.find("[name='num']").val()||'""';
    				rowData[x].price=$tr.find("[name='price']").val()||'""';
    			}
    		}
    		for(var i=0;i<rowData.length;i++){
    			var o = rowData[i];
    			if(o.skuId==skuId){
    				rowData.splice(i,1);
    			}
    		}
    		if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//手机端
    			var $patr =$(obj).parents("tr");
   	    	 	$patr.next(".detail-view").remove();
   	    	    $patr.remove();
    		}else{//pc端
   	    	 $("#purchaseOrder").bootstrapTable("destroy");
 	   	    	 $('#purchaseOrder').bootstrapTable({
 	   		    	   data:rowData,
 	   		    	   striped: true,
 	   		    	   onExpandRow: function(index, row, $detail){
 	   		    		   console.log(index,row);
 	   		    		   var cur_table = $detail.html('<table></table>').find('table');
 	   		   	       	   $(cur_table).bootstrapTable({   
 	   		   	             url: ctx+"/purchase/purchaseOrder/erpInfo?skuId="+row.skuId,
 	   		   		    	 contentType : "application/x-www-form-urlencoded",   //必须有
 	   		   		    	 striped: true,
 	   		   		    	 cache: false,
 	   		   	             responseHandler:function(sourceData){
 	   		   		    		 return {"data":sourceData.body.erpInfo};
 	   		   		    	 },
 	   		   		    	 columns: [
 	   		   		    		 {
 	   		   		    			 title:'名称：',
 	   		   		    			 field:'projectName'
 	   		   		    		 },
 	   		   		    		 {
 	   		   		    			 title:'类型：',
 	   		   		    			 field:'serviceType'
 	   		   		    		 },
 	   		   		    		 {
 	   		   		    			 title:'数量：',
 	   		   		    			 field:'amount'
 	   		   		    		 },
 	   		   		    		 {
 	   		   		    			 title:'日期：',
 	   		   		    			 field:'createDate'
 	   		   		    		 },
 	   		   		    		 {
 	   		   		    			 title:' ',
 	   		   		    			 field:'picUrl',
 	   		   		    			 formatter:function(value,row,index){
 	   		   		    				 if(row.picUrl){
 	   		   		    					 return '<img src='+row.picUrl+' style="float:right;width:60%">';
 	   		   		    				 }
 	   		   			               },
 	   		   		    		 }
 	   		   		    	 ]
 	   		   	       });
 	   		    	   },
 	   		    	   detailView: true,//父子表
 	   		    	   columns: [
 	   		    		   {
 	   		    	           title: '序号', //标题 可不加
 	   		    	           field:'scount',
 	   		    	           formatter: function (value, row, index) {
 	   		    	               return index + 1;
 	   		    	           },
 	   		    	       },
 	   		    		   {
 	   		    			   title:'SKUID',
 	   		    			   field:'skuId',
 	   			               formatter:function(value,row,index){
 	   			        	     return '<input class="noborder" value='+row.skuId+' name="sku" readOnly>';
 	   			               },
 	   		    		   },
 	   		    		   {
 	   		    		       field:'skuName',
 	   			               title: 'SKU'
 	   			           },
 	   			           {
 	   			               field: 'amount',
 	   			               title: '采购数量',
 	   			               class:'no-padding',
 	   			               formatter:function(value,row,index){
 	   			            	 if(row.amount&&(row.amount+"").trim()){
	 	   		            		   return '<input class="form-input" value='+row.amount+' onkeyup="checkAmount(this)" name="num" id="num" autocomplete="off" placeholder="请输入采购数量">';
	 	   		            	   }else{
	 	   		            		   return '<input class="form-input" onkeyup="checkAmount(this)" name="num" id="num" autocomplete="off" placeholder="请输入采购数量">';
	 	   		            	   }
 	   			               }
 	   			           }, { 
 	   			        	   field: 'price',
 	   			               title: '采购单价',
 	   			               class:'no-padding',
 	   			               formatter:function(value,row,index){
 	   			            	if(row.price!=undefined&&(row.price+"").trim()){
 	   		            		   return '<input class="form-input" value='+row.price+'  placeholder="请输入采购单价" id="price" onkeyup="checkPrice(this)" onblur="checkPrice(this)" name="price" autocomplete="off"/>';
 	   		            	   }else{
 	   		            		   return '<input class="form-input"  placeholder="请输入采购单价" id="price" onkeyup="checkPrice(this)" onblur="checkPrice(this)" name="price" autocomplete="off"/>';
 	   		            	   }
 	   			               }
 	   			          }, {
 	   			               title: '操作',
 	   			               formatter:function(value,row,index){
 	   			        	     return "<span class='btn btn-danger table-btn ' onclick='removeItem(this,"+row.skuId+")'>删除</span>"
 	   			               }
 	   			          }
 	   			   ]
 	   		    });
    		}
		}) 
    } 
    
   //====以下为新增代码
    //采购数量
    function checkAmount(obj){
    	obj.value=obj.value.replace(/\D/g,'');
    }
    function checkPrice(obj){
    	obj.value=obj.value.replace(/[^\d\.]/g,'');
    }
    var showSubTab=function(id){
 	   jp.open({
 		   type: 2,
 		   area: ['99%', '100%'],
 		   title:"SKU项目详情",
 		   content:ctx+"/purchase/purchaseOrder/purchaseDetail?skuId="+id
 	   });
    }
    //展开子表
    //父子表
	function onExpandRow(index, row, $detail){
		        initSubTable(index, row, $detail);
    }
		  function initSubTable(index, row, $detail){
		   console.log(index,row);
		   var cur_table = $detail.html('<table></table>').find('table');
	        $(cur_table).bootstrapTable({   
	             url: ctx+"/purchase/purchaseOrder/erpInfo?skuId="+row.skuId,
		    	 contentType : "application/x-www-form-urlencoded",   //必须有
		    	 striped: true,
		    	 cache: false,
	             responseHandler:function(sourceData){
		    		 return {"data":sourceData.body.erpInfo};
		    	 },
		    	 columns: [
		    		 {
		    			 title:'名称：',
		    			 field:'projectName'
		    		 },
		    		 {
		    			 title:'类型：',
		    			 field:'serviceType'
		    		 },
		    		 {
		    			 title:'数量：',
		    			 field:'amount'
		    		 },
		    		 {
		    			 title:'日期：',
		    			 field:'createDate'
		    		 },
		    		 {
		    			 title:' ',
		    			 field:'picUrl',
		    			 formatter:function(value,row,index){
		    				 if(row.picUrl){
		    					 return '<img src='+row.picUrl+' style="float:right;width:60%">';
		    				 }
			               },
		    		 }
		    	 ]
	       });
	   }
		  
		  
    function initData(){
        //加载sku数据
        $('#purchaseOrder').bootstrapTable({
        	//该请求地址需要改成采购单修改时的接口
           url:"${ctx}/purchase/purchaseOrder/findPurchaseOrderDetail?purchaseOrderId="+purchaseOrderId,
           contentType : "application/x-www-form-urlencoded", 
           striped: true,
           onExpandRow:onExpandRow,
           detailView: true,//父子表
      	   columns: [
      		   {
      	           title: '序号', //标题 可不加
      	           field:'scount',
      	           formatter: function (value, row, index) {
      	               return index + 1;
      	           },
      	       },
      		   {
      			   title:'SKUID',
      			   field:'skuId',
    	           formatter:function(value,row,index){
    	        	   return '<input class="noborder" value='+row.skuId+' name="sku" readOnly>';
    	           },
      		   },
      		   {
      		       field:'skuName',
    	           title: 'SKU',
    	       },
    	       {
    	           field: 'amount',
    	           title: '采购数量',
    	           class:'no-padding',
    	           formatter:function(value,row,index){
			         if(row.amount){
  		            	   return '<input class="form-input" value='+row.amount+' onkeyup="checkAmount(this)" name="num" id="num" autocomplete="off" placeholder="请输入采购数量">';
  		             }else{
  		           	   return '<input class="form-input" onkeyup="checkAmount(this)" name="num" id="num" autocomplete="off" placeholder="请输入采购数量">';
  		             }
			       }
    	        }, 
    	        {
    	           title: '采购单价',
    	           class:'no-padding',
    	           formatter:function(value,row,index){
    	        	   if(row.price!=undefined&&(row.price+"").trim()){
		            		return '<input class="form-input" value='+row.price+'  placeholder="请输入采购单价" id="price" onkeyup="checkPrice(this)" onblur="checkPrice(this)" name="price" autocomplete="off"/>';
		            	}else{
		            		return '<input class="form-input"  placeholder="请输入采购单价" id="price" onkeyup="checkPrice(this)" onblur="checkPrice(this)" name="price" autocomplete="off"/>';
		            	}
    	           }
    	        }, {
    	               title: '操作',
    	               formatter:function(value,row,index){
		            	   if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){
		            		   return "<span class='btn btn-danger table-btn ' onclick='removeItem(this,"+row.skuId+")'>删除</span> <span class='btn btn-primary table-btn ' onclick='showSubTab("+row.skuId+")'>详情</span>";
		            	   }else{
		            		   return "<span class='btn btn-danger table-btn ' onclick='removeItem(this,"+row.skuId+")'>删除</span>";
		            	   }
		               }
    	     
    	          }
    	   ]
        });
    }
    $(function(){
    	initData();
    	if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端
	   		 $('#purchaseOrder').bootstrapTable("toggleView");
	   	}
    });
</script>


</html>
